package com.edgar.couchdb;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;

import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;

public class CouchDbTest {

    private static HttpClient httpClient;
    private static CouchDbInstance couchDbInstance;
    private static CouchDbConnector db;
    private static  int threadCount = 8;
    private static  int perThreadCount = 3000;

    public static void main(String[] args) throws MalformedURLException, InterruptedException {
//        if(Integer.parseInt(args[0]) > 0 && Integer.parseInt(args[1]) > 0) {
//            threadCount = Integer.parseInt(args[0]);
//            perThreadCount = Integer.parseInt(args[1]);
//        }else {
//            threadCount = 4;
//            perThreadCount = 4;
//        }

        calc(threadCount, perThreadCount);
    }

    public static void calc(int threadCount, int perThreadCount) throws MalformedURLException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Vector<Thread> threads = new Vector<>();
        httpClient = new StdHttpClient.Builder().url("http://172.16.18.10:5984").username("admin").password("password").build();
        couchDbInstance = new StdCouchDbInstance(httpClient);
        db = new StdCouchDbConnector("test", couchDbInstance);
        db.createDatabaseIfNotExists();
        for (int i = 0; i < threadCount; i++) {
            SubThreadTps subThreadTps = new SubThreadTps(perThreadCount);
            Thread thread = new Thread(subThreadTps);
            threads.add(thread);
            thread.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("总耗时：" + (endTime-startTime) / 1000.0 + "s");
        System.out.println("tps：" + (threadCount*perThreadCount) / ((endTime-startTime) / 1000.0) + "s");
    }

    private static class SubThreadTps implements Runnable {
        int count = 0;
        public SubThreadTps(int count) {
            this.count = count;
        }
        @Override
        public void run() {
            Map<String, String> doc = new HashMap<String, String>();
            if (this.count > 0) {
                for (int i = 0; i < this.count; i++) {
                    doc.put("_id",  UUID.randomUUID().toString());
                    doc.put("itemNumber", "itemNumberiii");
                    doc.put("comment", "comment");
                    db.create(doc);
                    doc.clear();
                }
            }
        }
    }
}
